﻿using eslib.nnp5.serializer;

namespace eslib.nnp5
{
    /// <summary>
    /// 序列化类型数据包
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SerializedPkg<T> : IPackage
        where T : new()
    {
        /// <summary>
        /// 包数据
        /// </summary>
        public byte[] pkgData { get; private set; }

        /// <summary>
        /// 包对象
        /// </summary>
        public T obj
        {
            get
            {
                return GetSerializer().Deserialize<T>(pkgData);
            }
        }


        static ISerializer GetSerializer()
        {
            return new ODATASerializer();
        }


        /// <summary>
        /// 创建新数据包
        /// </summary>        
        /// <returns></returns>
        public static SerializedPkg<T> CreateNew(T obj)
        {
            var spkg = new SerializedPkg<T>();
            spkg.pkgData = GetSerializer().Serialize(obj);
            return spkg;
        }


        /// <summary>
        /// 以缓存转换包，错误时抛出SerializeException异常
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static SerializedPkg<T> Transfer(byte[] buffer)
        {
            var spkg = new SerializedPkg<T>();
            spkg.pkgData = buffer;
            return spkg;
        }


        protected SerializedPkg()
        {
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public byte[] GetBuffer()
        {
            return pkgData;
        }


    }
}
